package org.sction.security.log;

import java.lang.reflect.Method;
import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.sction.action.annotation.Action;
import org.sction.action.annotation.Controller;
import org.sction.action.core.ActionUtils;
import org.sction.action.core.BaseAction;
import org.sction.security.shiro.ShiroUser;


public class AccessLogBaseImpl implements AccessLog {
	private static final Logger logger = Logger
			.getLogger(AccessLogBaseImpl.class);

	public void beforeLog(Action a, Object obj, Method method, Object[] args) {
		BaseAction ba = null;
		HttpServletRequest request = null;
		Controller c = obj.getClass().getAnnotation(Controller.class);

		String info = "";
		ShiroUser user = ActionUtils.getShiroUser();
		if (obj instanceof BaseAction) {
			ba = (BaseAction) obj;
			request = ba.getRequest();
			info = "来自:" + request.getRemoteHost() + ":"
					+ request.getRemotePort() + "的";

		}
		if (user != null) {
			info += "用户:" + user.getName() + "[" + user.getLoginid() + "]";
		} else if (ba != null) {
			user = ba.getUser();
			info += "用户:" + user.getName() + "[" + user.getLoginid() + "]";
		}

		logger.info(info);
		if (c != null) {
			String cvalue = "".equals(c.value()) ? obj.getClass()
					.getSimpleName() : c.value();
			info = "调用模块:" + c.name() + "[" + cvalue + "]的";

		}
		String avalue = "".equals(a.value()) ? method.getName() : a.value();
		info += ("方法:" + a.name() + "[" + avalue + "]");
		info += "参数为：";
		for (int i = 0; i < args.length; i++) {
			Object object = args[i];
			if (i == args.length - 1) {
				info += object;
			} else {
				info += (object + ",");
			}
		}
		logger.info(info);
		if (ba != null) {
			info = "请求参数为：";
			Enumeration<String> rpns = request.getParameterNames();
			while (rpns.hasMoreElements()) {
				String name = rpns.nextElement();
				String value = request.getParameter(name);
				if (rpns.hasMoreElements()) {
					info += (name + "=" + value + ",");
				} else {
					info += (name + "=" + value);
				}
			}
			logger.info(info);
			info = ("访问者设备信息：");
			info += (request.getHeader("User-Agent") + " Cookie:" + request
					.getHeader("Cookie"));
			logger.info(info);
		}
	}

	public void AfterLog(Action a, Object obj, Method method, Object result) {

	}

	public void notPermissionsLog(Action a, Object obj, Method method,
			Object[] args, String permissions) {
		logger.error("无权访问，需要权限：" + permissions);
	}

}
